package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"oct31-hw/cache"
	"oct31-hw/models"
	"time"
)

func CollectionList(c *gin.Context) {
	var list []models.CollectionList

	/*
		SELECT
		  collections.id AS CollectionID,
		  users.username AS Username,
		  collections.uid AS Uid,
		  collections.pid AS Pid,
		  posts.title AS Title,
		  posts.content AS content,
		  posts.author AS Author
		FROM
		  collections
		  LEFT JOIN users ON users.id = collections.uid
		  LEFT JOIN posts ON posts.id = collections.pid
	*/
	redis_key := "collection_list"
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Table("collections").
			Select(
				"collections.id AS CollectionID",
				"users.username AS Username",
				"collections.uid AS Uid",
				"collections.pid AS Pid",
				"posts.title AS Title",
				"posts.content AS content",
				"posts.author AS Author",
			).
			Joins("LEFT JOIN users ON users.id = collections.uid").
			Joins("LEFT JOIN posts ON posts.id = collections.pid").
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &list)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "收藏列表获取成功",
		"data": list,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	redis_key := "post_detail" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Where("id = ?", id).First(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &post)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "详情获取成功",
		"data": post,
	})
	return
}
